package com.zyx.spring5msb.aopbasic.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/28 14:36
 */
@Component
@Aspect
@Order(1)
public class SecurityUtil {

    @Pointcut("execution(public * com.zyx.spring5msb.aopbasic.service.CalculatorImpl.*(..))")
    public void noArgsPointCut() {
    }

    @Before(value = "execution(public * com.zyx.spring5msb.aopbasic.service.CalculatorImpl.*(..)) && args(i2,j2)", argNames = "joinPoint,i2,j2")
    public static void start(JoinPoint joinPoint, Integer i2, Integer j2) {
        // 获取方法签名
        Signature signature = joinPoint.getSignature();
        // 获取参数信息
        Object[] args = joinPoint.getArgs();
        System.out.println("security---" + signature.getName() + "方法开始执行, 参数为:" + Arrays.toString(args));
    }

    @AfterReturning(value = "execution(public * com.zyx.spring5msb.aopbasic.service.CalculatorImpl.*(..))", returning = "result")
    public static void stop(JoinPoint joinPoint, Object result) {
        Signature signature = joinPoint.getSignature();
        System.out.println("security---" + signature.getName() + "方法执行结束, 返回结果:" + result);
    }

    @AfterThrowing(value = "execution(public * com.zyx.spring5msb.aopbasic.service.CalculatorImpl.*(..))", throwing = "e")
    public static void logerror(JoinPoint joinPoint, Exception e) {
        Signature signature = joinPoint.getSignature();
        System.out.println("security---" + signature.getName() + "方法执行异常: " + e.getMessage());
    }

    @After(value = "noArgsPointCut()")
    public static void logfinal() {
        System.out.println("security---方法结束, 执行finally中代码块");
    }


    @Around(value = "noArgsPointCut()")
    public Object around(ProceedingJoinPoint pjp) {
        Object result = null;
        Signature signature = pjp.getSignature();
        Object[] args = pjp.getArgs();
        try {
            System.out.println("security---环绕通知start：" + signature.getName() + "方法开始执行了, 参数为:" + Arrays.toString(args));
            result = pjp.proceed(args);
            System.out.println("security---环绕通知stop：" + signature.getName() + "方法开始结束了, 结果为:" + result);
        } catch (Throwable throwable) {
            System.out.println("security---环绕异常通知："+signature.getName()+"出现异常");
            throwable.printStackTrace();
        } finally {
            System.out.println("security---环绕返回通知：" + signature.getName() + "方法返回结果是：" + result);
        }

        return result;
    }


}
